package service

import (
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"fmt"
	"time"

	"github.com/google/uuid"
)

type TokenService struct {
	db *sql.DB
}

func NewTokenService(db *sql.DB) *TokenService {
	return &TokenService{db: db}
}

// GenerateToken 生成新的Token
func (s *TokenService) GenerateToken(userID int) (string, error) {
	// 生成Token
	token := generateTokenString(userID)

	// 设置过期时间（30天）
	expireTime := time.Now().AddDate(0, 1, 0)

	// 保存到数据库
	_, err := s.db.Exec(`
		INSERT INTO wqyf_user_tokens (user_id, token, expire_time)
		VALUES (?, ?, ?)
	`, userID, token, expireTime)

	if err != nil {
		return "", err
	}

	return token, nil
}

// ValidateToken 验证Token
func (s *TokenService) ValidateToken(token string) (int, error) {
	var (
		userID     int
		expireTime time.Time
	)

	err := s.db.QueryRow(`
		SELECT user_id, expire_time
		FROM wqyf_user_tokens
		WHERE token = ?
	`, token).Scan(&userID, &expireTime)

	if err != nil {
		return 0, err
	}

	// 检查是否过期
	if time.Now().After(expireTime) {
		return 0, fmt.Errorf("token expired")
	}

	return userID, nil
}

// RevokeToken 撤销Token
func (s *TokenService) RevokeToken(token string) error {
	_, err := s.db.Exec(`
		DELETE FROM wqyf_user_tokens
		WHERE token = ?
	`, token)
	return err
}

// CleanExpiredTokens 清理过期Token
func (s *TokenService) CleanExpiredTokens() error {
	_, err := s.db.Exec(`
		DELETE FROM wqyf_user_tokens
		WHERE expire_time < NOW()
	`)
	return err
}

// generateTokenString 生成Token字符串
func generateTokenString(userID int) string {
	// 组合用户ID、UUID和时间戳
	data := fmt.Sprintf("%d:%s:%d", userID, uuid.New().String(), time.Now().UnixNano())
	
	// 计算MD5
	hash := md5.New()
	hash.Write([]byte(data))
	return hex.EncodeToString(hash.Sum(nil))
} 